#define _CRT_SECURE_NO_WARNINGS 1
#include"slist.h"


void PrintList(struct SLNode* phead)
{
	while (phead != NULL)
	{
		printf("%d-> ", phead->data);
		phead = phead->next;
	}
	printf("NULL\n");
}
struct SLNode* BuyNewNode(SLDataType x)
{
	SLN* newnode = (SLN*)malloc(sizeof(SLN));
	newnode->data = x;
	newnode->next = NULL;
}
//βɾ
void SListPushBack(int** pphead,SLDataType x)
{
	SLN* newnode = BuyNewNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLN* cur = *pphead;
		while (cur->next != NULL)
		{
			cur = cur->next;
		}
		cur->next = newnode;
	}
}
//ͷɾ
void SListPushFront(struct SLNode** pphead, SLDataType x)
{
	SLN* newnode = BuyNewNode(x);
	SLN* next = *pphead;
	*pphead = newnode;
	(*pphead)->next = next;
}

void SListPopBack(struct SLNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	else if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		assert(*pphead);
		SLN* prev = *pphead;
		SLN* cur = *pphead;
		while (cur->next != NULL)
		{
			prev = cur;
			cur = cur->next;
		}
		free(cur);
		prev->next = NULL;
		cur = NULL;
	}
}

void SListPopFront(struct SLNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}

	SLN* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}

struct SLNode* SearchList(struct SLNode** pphead, SLDataType x)
{
	SLN* cur = *pphead;

	while (cur != NULL)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void InsertList(struct SLNode** pphead, SLDataType x, struct SLNode* pos)
{
	SLN* newnode = BuyNewNode(x);
	if (*pphead == pos)
	{
		SListPushFront(pphead, x);
	}
	else
	{
		SLN* prev = *pphead;
		SLN* cur = *pphead;

		while (cur != pos)
		{
			prev = cur;
			cur = cur->next;
		}
		prev->next = newnode;
		newnode->next = cur;
	}
}

void SListErase(struct SLNode** pphead, struct SLNode* pos)
{
	if (*pphead == NULL)
	{
		return;
	}
	else if (*pphead == pos)
	{
		SListPopFront(pphead);
	}
	else
	{
		SLN* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}

}